package com.cn.xiongmeng.czlxz;

import static com.anythink.network.gdt.GDTATConst.DEBUGGER_CONFIG.GDT_NETWORK;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;

import android.os.Handler;
import android.os.Looper;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.anythink.core.api.ATDebuggerConfig;
import com.anythink.core.api.ATSDK;
import com.cn.xiongmeng.czlxz.activity.IndexActivity;
import com.cn.xiongmeng.czlxz.databinding.ActivityMainBinding;
import com.cn.xiongmeng.czlxz.network.HttpClient;
import com.cn.xiongmeng.czlxz.taku.SplashAd;
import com.cn.xiongmeng.czlxz.ui.LoadingFragment;

import net.security.device.api.SecurityDevice;
import net.security.device.api.SecurityCode;
import net.security.device.api.SecurityToken;

import java.util.HashMap;
import java.util.Map;

import com.cn.xiongmeng.czlxz.network.HttpClient;
import com.cn.xiongmeng.czlxz.utils.AliyunRiskUtils;
import com.cn.xiongmeng.czlxz.utils.DeviceIdUtils;
import com.cn.xiongmeng.czlxz.utils.DeviceStateChecker;
import com.cn.xiongmeng.czlxz.utils.IntervalControler;
import com.cn.xiongmeng.czlxz.utils.OaidUtils;
import com.cn.xiongmeng.czlxz.utils.PrivacyUtils;

import com.cn.xiongmeng.czlxz.utils.SelfRiskUtils;
import com.github.gzuliyujiang.oaid.DeviceIdentifier;


import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private ActivityMainBinding binding;
    private SharedPreferences prefs;
    private boolean privacyIsAgreed;
    private LinearLayout dialogPrivacy;
    private TextView tvPolicyContent;
    private Button btnDisagree;
    private Button btnAgree;
    private LoadingFragment loadingFragment;
    private HttpClient httpClient;

    private boolean needJump;

    private boolean deviceState;
    // private static String ALIYUN_APPKEY = "shf68228bdhs168d70dedd58a0e4a093";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        prefs = this.getSharedPreferences("AppPrefs", Context.MODE_PRIVATE);
        privacyIsAgreed = false;

        //loadingImage = findViewById(R.id.loading_image);
        dialogPrivacy = findViewById(R.id.dialog_privacy);
        tvPolicyContent = findViewById(R.id.tv_policy_content);
        btnDisagree = findViewById(R.id.btn_disagree);
        btnAgree = findViewById(R.id.btn_agree);
        loadingFragment = new LoadingFragment();

        httpClient = new HttpClient(this);

        privacyConfirm();

        DeviceIdentifier.register(getApplication());
    }
    /* 隐私政策展示弹窗 */
    private void privacyConfirm(){
        PrivacyUtils.privacyConfirm(this, dialogPrivacy, tvPolicyContent, btnDisagree, btnAgree, new PrivacyUtils.PrivacyConfirmCallback(){
            @Override
            public void onConfirm(boolean isAgreed) {
                if (!isAgreed) {
                    // 用户不同意“用户协议”、“隐私政策”，退出应用
                    finishAffinity();
                    return;
                }
                // 用户同意“用户协议”、“隐私政策”，进行oaid申请
                //oaidConfirm();
                init(true);
            }
        });
    }

    /* oaid请求弹窗 */
    private void oaidConfirm(){
        OaidUtils.oaidConfirm(this, new OaidUtils.OaidConfirmCallback(){
            @Override
            public void onConfirm(boolean isAgreed) {
                init(isAgreed);
            }
        });
    }
    /*
    * 1、Loading展示
    * 2、阿里云风控
    * 3、Loading取消
    * 4、跳转
    *  */
    private void init(boolean oaidIsAgreed) {
        // 开启后台线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 1、Loading动画展示
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showFragment(loadingFragment, "fragment_loading");
                    }
                });
                // 2、禁止频繁打开APP
                Runnable controlledFunc = () -> {
                    try {
                        Thread.sleep(2000);
                        System.exit(0);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                };
                IntervalControler.intervalControlForStartAPP(MainActivity.this, controlledFunc, "preStartApp", 120);
                // 3、阿里云风控
                AliyunRiskUtils.aliyunRisk(MainActivity.this, oaidIsAgreed, new AliyunRiskUtils.AliyunRiskCallback() {
                    @Override
                    public void onAliyunRisk(int code) {
                        if (code != 200){
                            finishAffinity();
                            return;
                        }
                        // 4、Self风控
                        SelfRiskUtils.selfRisk(MainActivity.this, oaidIsAgreed, new SelfRiskUtils.SelfRiskCallback() {
                            @Override
                            public void onSelfRisk(int code) {
                                if (code != 200){
                                    finishAffinity();
                                    return;
                                }

                                initAds();
                            }
                        });
                    }
                });
                // 4、Self风控
                /*SelfRiskUtils.selfRisk(MainActivity.this, oaidIsAgreed, new SelfRiskUtils.SelfRiskCallback() {
                    @Override
                    public void onSelfRisk(int code) {
                        if (code != 200){
                            finishAffinity();
                            return;
                        }

                        initAds();
                    }
                });*/
                /*try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }*/
                // initAds();
            }
        }).start();
    }
    // 广告相关初始化
    private void initAds(){
        // 开屏广告初始化、加载
        MainApplication app = (MainApplication)getApplication();
        app.initSplashAd(MainActivity.this);
        // Banner广告初始化
        app.initBannerView(MainActivity.this);
        // 插屏广告初始化、加载
        app.initInterstitialAd(MainActivity.this);
        // 激励视频广告初始化、加载
        app.initRewardVideoAd(MainActivity.this);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 开屏广告展示
        showSplashAd();
        // 跳转页面，由开屏广告的回调选择执行
    }
    // 展示 开屏广告
    private void showSplashAd(){
        FrameLayout splashAdContainer = findViewById(R.id.splash_ad_container);
        SplashAd.showSplashAd(this, splashAdContainer);
    }
    public void jumpToNextActivity() {
        if (!needJump) {
            needJump = true;
            return;
        }
        Intent intent = new Intent(this, IndexActivity.class);
        startActivity(intent);
        finish();
    }
    private void showFragment(Fragment fragment, String str) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        if (fragment.isAdded()) {
            fragmentTransaction.show(fragment);
        } else {
            fragmentTransaction.add(R.id.fragment_container, fragment, str);
        }
        fragmentTransaction.commit();
    }
    private void removeFragment(Fragment fragment){
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        if (fragment.isAdded()) {
            fragmentTransaction.remove(fragment);
        }
        fragmentTransaction.commit();
    }
    @Override
    protected void onStart() {
        super.onStart();

        Log.d(TAG, "onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
        if (needJump) {
            jumpToNextActivity();
        }
        needJump = true;
    }

    @Override
    protected void onPause() { // 1、用户把应用放到后台 2、用户点击开屏广告
        super.onPause();
        Log.d(TAG, "onPause");
        needJump = false;
    }

    @Override
    protected void onStop() {
        super.onStop();

        Log.d(TAG, "onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        Log.d(TAG, "onDestroy");
    }
}